// 将Unicode编码转换回emoji
function UTF16Tocontent(str) {
    return str.replace(/\\u([a-fA-F0-9]{4,5})/g, function (match, grp) {
        return String.fromCharCode(parseInt(grp, 16));
    });
}
layui.use(function () {
    var flow = layui.flow;
    var $ = layui.jquery;
    var layer = layui.layer;
    if (sessionStorage.getItem("user") != null) {
        const user = JSON.parse(sessionStorage.getItem("user"))
        $("#nickname").text(user.userinfo.nickname)
        $("#username").text("@" + user.username)
        $("#useravatar").prop("src", "data:image/png;base64," + user.avatar)
        $("#pubuseravatar").prop("src", "data:image/png;base64," + user.avatar)
    }
    var allVue = [];
    $("#zzgz").on('click', function () {
        loadMore(user.uid);
    })

    $("#ForYa").on('click', function () {
        loadMore();
    })

    // 加载帖子的方法
    function loadMore(uid) {
        for (let i = 0; i < allVue.length; i++) {
            allVue[i].$destroy();
        }
        $("#ID-flow-demo").empty()
        let url = uid != undefined ? "http://169.254.202.137:8080/GetFollowerPost?uid=" + uid + "&" : "http://169.254.202.137:8080/GetPost?"
        flow.load({
            elem: '#ID-flow-demo', // 流加载容器
            isAuto: true,
            done: function (page, next) {
                // 定义一个变量，用来存储拼接的html字符串
                var postsid = [];
                var divid = [];
                var html = '';
                // 使用jquery的ajax方法，向后端发送请求，获取数据
                $.ajax({
                    type: "GET",
                    url: url + "page=" + page, // 后端的Servlet路径，加上页码参数
                    dataType: "json", // 预期返回的数据类型是json
                    success: function (data) {
                        function generateUniqueId(postId) {
                            const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
                            const randomLetter = alphabet[Math.floor(Math.random() * alphabet.length)];
                            return `${postId}-${randomLetter}`;
                        }

                        postsid = [];
                        var totalPage = (data.count + 5 - 1) / 5;
                        // 如果请求成功，遍历返回的数据，将每个帖子和评论的信息拼接成html字符串
                        for (var i = 0; i < data.data.length; i++) {
                            var post = data.data[i]; // 获取每个帖子对象
                            postsid.push(post.pid)
                            let date = new Date(post.ptime)
                            // 获取该时间的毫秒数
                            var dateMs = date.getTime();

                            // 获取当前时间的毫秒数
                            var nowMs = Date.now();

                            var dateyear = date.getFullYear();

                            var nowyear = new Date().getFullYear();

                            // 计算两个时间的差值，单位为毫秒
                            var diffMs = nowMs - dateMs;

                            // 将差值除以 1000，得到两个时间的差值，单位为秒
                            var diffSec = Math.floor(diffMs / 1000);

                            // 定义一个空字符串，用于存储拼接的结果
                            var diffStr = "";

                            // 判断差值的大小，拼接成相应的字符串
                            if (dateyear != nowyear) {
                                diffStr = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
                            } else if (diffSec < 60) {
                                // 如果差值小于 60 秒，显示为几秒
                                diffStr = diffSec + "秒前";
                            } else if (diffSec < 3600) {
                                // 如果差值小于 3600 秒，显示为几分钟
                                diffStr = Math.floor(diffSec / 60) + "分钟前";
                            } else if (diffSec < 86400) {
                                // 如果差值小于 86400 秒，显示为几小时
                                diffStr = Math.floor(diffSec / 3600) + "小时前";
                            } else if (diffSec < 604800) {
                                diffStr = Math.floor(diffSec / 86400) + "天前";
                            } else if (diffSec < 31536000) {
                                diffStr = date.getMonth() + 1 + "月" + date.getDate() + "日";
                            } else {
                                diffStr = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
                            }
                            let uniquedivid = generateUniqueId(post.pid);
                            // 拼接帖子的信息
                            html += '<div class="list-group" id="post-' + uniquedivid + '" @click="handleClick">';
                            divid.push(uniquedivid);
                            html += '<img class="avatar" src="data:image/png;base64,' + post.publishaccountInfo.avatar + '">' + '<p id="uid" hidden>' + post.publishaccountInfo.uid + '</p>' + '<p hidden>' + post.pid + '</p>'
                            html += '<span class="nickname">' + post.userinfo.nickname + '</span>' + '<span class="username">@' + post.publishaccountInfo.username + '</span>&nbsp;·&nbsp;' + '<time datetime="' + post.ptime + '" id="time-' + post.pid + '" lay-src="' + post.ptime + '">' + diffStr + '</time>';
                            html += '<p class="content">' + UTF16Tocontent(post.pcontent) + '</p>';
                            if (post.pimage && post.pvideo) { // 如果帖子有图片，显示图片
                                html += '<div class="imgvideo"><div class="img"><img class="image" src="data:image/png;base64,' + post.pimage + '">' + '<div class="videos"><video class="video" src="http://169.254.202.137:8080/' + post.pvideo + '"controls></video></div>' + '</div></div>';
                            } else if (post.pimage) {
                                html += '<div class="imgvideo"><div class="img"><img class="image" src="data:image/png;base64,' + post.pimage + '"></div></div>'
                            } else if (post.pvideo) {
                                html += '<div class="imgvideo"><div class="img"><video class="video" src="http://169.254.202.137:8080/' + post.pvideo + '"controls></video></div></div>'
                            }

                            html += '<div class="info"><i class="like" :class="likeClass" @click.stop="Like()"></i><span class="infotext" id="infotext">{{ likes }}</span><i class="icon ice-message"></i><span class="infotext">{{ commentscount }}</span></div>'
                            html += '</div>';
                        }
                        // 调用next方法，将拼接好的html字符串添加到容器元素中，并传入总页数
                        // 假设总页数是10
                        next(html, page < totalPage);

                        for (let i = 0; i < postsid.length; i++) {
                            let pid = postsid[i];
                            let did = divid[i];
                            let vue = new Vue({
                                el: '#post-' + did,
                                data: {
                                    islike: false,
                                    likes: 0,
                                    commentscount: 0,
                                },
                                computed: {
                                    likeClass() {
                                        return this.islike ? 'icon ice-heart-on like-animation' : 'icon ice-heart-off';
                                    },
                                },
                                methods: {
                                    Like() {
                                        let icon = this.$el.querySelector('.icon');
                                        if (this.islike) {
                                            // 取消点赞
                                            this.likes--;
                                            icon.classList.remove('ice-heart-on');
                                            icon.classList.add('ice-heart-off');

                                            // 发送取消点赞请求
                                            $.ajax({
                                                url: "http://169.254.202.137:8080/unlike",
                                                type: "POST",
                                                data: { pid: pid, uid: user.uid },
                                                success: function (response) {

                                                },
                                                error: function (xhr, status, error) {
                                                    console.error(xhr.responseText);
                                                    // 在这里处理取消点赞错误响应
                                                }
                                            });
                                        } else {
                                            // 点赞
                                            this.likes++;
                                            icon.classList.remove('ice-heart-off');
                                            icon.classList.add('ice-heart-on', 'like-animation');

                                            // 发送点赞请求
                                            $.ajax({
                                                url: "http://169.254.202.137:8080/like",
                                                type: "POST",
                                                data: { pid: pid, uid: user.uid },
                                                success: function (response) {

                                                },
                                                error: function (xhr, status, error) {
                                                    console.error(xhr.responseText);
                                                    // 在这里处理点赞错误响应
                                                }
                                            });
                                        }
                                        this.islike = !this.islike;
                                    },
                                    ViewPost() {
                                        let url = 'ViewPost.html?pid=' + pid;
                                        window.location.href = url;
                                    },
                                    handleClick(event) {
                                        const target = event.target
                                        if (target.classList.contains('like')) {
                                            this.Like()
                                        } else {
                                            this.ViewPost()
                                        }
                                    }
                                }
                            });
                            allVue.push(vue);
                            let uid = user && user.uid ? user.uid : '';

                            $.ajax({
                                type: 'get',
                                url: 'http://169.254.202.137:8080/GetLikeAndComment?pid=' + pid + "&uid=" + uid,
                                dataType: 'json',
                                success: function (res) {
                                    vue.likes = res.data.likes;
                                    vue.commentscount = res.data.commentscount;
                                    vue.islike = res.data.islike;
                                }
                            });
                        }

                    },
                    error: function (error) {
                        // 如果请求失败，显示错误信息
                        alert("服务器异常!!");
                    }
                });
            }
        });
    }

    loadMore();
    // 获取容器元素对象
    let element = $("#ID-flow-demo");


    // 定义一个变量，用于存储弹出层的索引
    let index;

    // 监听容器元素的 mouseover 事件
    element.on("mouseover", "time", function (e) {
        // 获取触发事件的目标元素
        let target = e.target;

        // 判断目标元素是否是 time 标签
        if (target.tagName === "TIME") {
            // 获取 time 标签的 lay-src 属性的值
            let datetime = target.getAttribute("lay-src");

            let timestr = "";

            let date = new Date(datetime);

            let hour = date.getHours();
            let minute = date.getMinutes();
            let month = (date.getMonth() + 1);
            let day = date.getDate();
            let year = date.getFullYear();
            if (hour <= 12)
                timestr += "上午"
            else
                timestr += "下午"

            timestr += hour + ": " + minute + " ·" + month + "月" + day + "，" + year;

            // 使用 layer 的 tips 方法，显示 time 标签的值
            index = layer.tips(timestr, target, {
                tips: [3, '#3595CC'], // 设置提示框的方向和颜色
                time: 0 // 设置提示框不自动关闭
            });
        }
    });

    // 监听容器元素的 mouseout 事件
    element.on("mouseout", "time", function (e) {
        // 获取触发事件的目标元素
        let target = e.target;

        // 判断目标元素是否是 time 标签
        if (target.tagName === "TIME") {
            // 使用 layer 的 close 方法，隐藏 time 标签的值
            layer.close(index);
        }
    });

    // 定义防抖函数
    function debounce(func, wait, immediate) {
        let timeout;
        return function () {
            const context = this,
                args = arguments;
            const later = function () {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    }

    var tipsHovered = false; // 添加一个变量来跟踪鼠标是否悬停在提示框上
    let tipsIndex; // 声明一个变量来存储提示框的索引
    let interval; // 声明一个变量来存储定时器

    // 监听容器头像元素的 mouseover 事件，并应用防抖
    element.on("mouseover", "img.avatar", debounce(function (e) {
        // 如果提示框已经存在，则直接返回
        if (tipsIndex !== undefined) {
            return;
        }

        // 获取触发事件的目标元素
        let target = e.target;
        let username = $(this).parent('div.list-group').find('.username').text()
        let useruid = $(this).parent('div.list-group').find('p#uid').text()
        // 判断目标元素是否是 img 标签
        if (target.tagName === "IMG") {
            // 获取 img 标签的 src 属性的值
            let personinfoavatar = target.getAttribute("src");

            let personInfo = '';
            personInfo += '<div id="personInfo" class="personInfo" @click="handleClick"><img class="avatar" src="' + personinfoavatar + '"></img><span class="nickname">{{ userinfo.nickname }}</span><span class="username">' + username + '</span>';
            personInfo += '<div class="info"><span class="follower">{{ followers }}' + '</span><span class="followertext">正在关注</span><span class="followee">{{ followees }}' + '</span><span class="followeetext">关注者</span><span class="LikeCount">{{ LikeCount }}' + '</span><span class="LikeCounttext">获赞</span><p class="bio">{{ userinfo.bio }}</p></div>';
            personInfo += '<div class="FollowInfo"><button class="layui-btn layui-bg-blue followbtn" @click.stop="Follow()">{{ isFollow ? "取消关注" : "关注" }}</button></div>'

            // 使用 layer 的 tips 方法，显示 img 标签的值
            tipsIndex = layer.tips(personInfo, target, {
                tips: [2, '#FFF'], // 设置提示框的方向和颜色
                time: 0, // 设置提示框不自动关闭
                success: function (layero) {
                    let vue = new Vue({
                        el: '#personInfo',
                        data: {
                            isFollow: false,
                            followers: 0,
                            followees: 0,
                            LikeCount: 0,
                            userinfo: '',
                        },
                        mounted() {
                            this.checkFollow();
                            this.GetFans();
                            this.GetFollowers();
                            this.GetLikeCount();
                            this.GetUserInfo();
                        },
                        methods: {
                            handleClick(event) {
                                const target = event.target
                                if (target.classList.contains('followbtn')) {
                                    this.Follow()
                                } else {
                                    this.ViewPerson()
                                }
                            },
                            ViewPerson() {
                                let url = 'Personal.html?uid=' + this.userinfo.useruid;

                                window.location.href = url;
                            },
                            Follow() {
                                if (user.uid === useruid) {
                                    layui.layer.msg('不能对自己进行此操作', { icon: 2, time: 1500 }, function () {

                                    });
                                    return;
                                }
                                if (this.isFollow) {
                                    // 取消关注
                                    this.followees--;
                                    this.isFollow = false;
                                    // 发送取消关注请求
                                    $.ajax({
                                        url: "http://169.254.202.137:8080/UnFollow",
                                        type: "POST",
                                        data: { Follower: user.uid, Followee: useruid },
                                        success: function (response) {

                                        },
                                        error: function (xhr, status, error) {
                                            console.error(xhr.responseText);
                                            // 在这里处理取消关注错误响应
                                        }
                                    });
                                } else {
                                    this.followees++;
                                    this.isFollow = true;
                                    // 发送关注请求
                                    $.ajax({
                                        url: "http://169.254.202.137:8080/Follow",
                                        type: "POST",
                                        data: { Follower: user.uid, Followee: useruid },
                                        success: function (response) {

                                        },
                                        error: function (xhr, status, error) {
                                            console.error(xhr.responseText);
                                            // 在这里处理关注错误响应
                                        }
                                    });
                                }
                            },
                            checkFollow() {
                                $.ajax({
                                    url: 'http://169.254.202.137:8080/isFollow?',
                                    data: 'Follower=' + user.uid + '&Followee=' + useruid,
                                    type: 'Post',
                                    dataType: 'json',
                                    success: (res) => { // 使用箭头函数确保正确的 this 指向
                                        this.isFollow = res.data;
                                    }
                                })
                            },
                            GetFans() {
                                $.ajax({
                                    url: 'http://169.254.202.137:8080/GetFollower?',
                                    data: 'Follower=' + useruid,
                                    type: 'Post',
                                    dataType: 'json',
                                    success: (res) => { // 使用箭头函数确保正确的 this 指向
                                        this.followers = res.data;
                                    }
                                })
                            },
                            GetFollowers() {
                                $.ajax({
                                    url: 'http://169.254.202.137:8080/GetFollowee?',
                                    data: 'Followee=' + useruid,
                                    type: 'Post',
                                    dataType: 'json',
                                    success: (res) => { // 使用箭头函数确保正确的 this 指向
                                        this.followees = res.data;
                                    }
                                })
                            },
                            GetLikeCount() {
                                $.ajax({
                                    url: 'http://169.254.202.137:8080/GetLikesCount?',
                                    data: 'uid=' + useruid,
                                    type: 'Post',
                                    dataType: 'json',
                                    success: (res) => { // 使用箭头函数确保正确的 this 指向
                                        this.LikeCount = res.data;
                                    }
                                })
                            },
                            GetUserInfo() {
                                $.ajax({
                                    url: 'http://169.254.202.137:8080/GetUserInfo?',
                                    data: 'useruid=' + useruid,
                                    type: 'Post',
                                    dataType: 'json',
                                    success: (res) => { // 使用箭头函数确保正确的 this 指向
                                        this.userinfo = res.data;
                                    }
                                })
                            }
                        }
                    });
                    // 给提示框添加鼠标悬停和移出事件
                    $(layero).hover(function () {
                        tipsHovered = true; // 鼠标悬停在提示框上
                    }, function () {
                        tipsHovered = false; // 鼠标移出提示框
                    });
                }
            });
            // 定时检查鼠标是否悬停在提示框上，并根据情况关闭提示框
            interval = setInterval(function () {
                if (!tipsHovered) { // 如果鼠标不悬停在提示框上，则关闭提示框
                    // 使用 layer 的 close 方法，隐藏提示框
                    layer.close(tipsIndex);
                    tipsIndex = undefined
                    clearInterval(interval); // 清空定时器
                }
            }, 1000); // 每隔 1000 毫秒执行一次检查
        }
    }, 300)); // 延迟 300 毫秒执行

    let currentVideo;

    function isElementInViewport(el) {
        if (!el) return false;
        const rect = el.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }

    function playVideo(video) {
        if (isElementInViewport(video)) {
            video.play();
            currentVideo = video;
        } else {
            video.pause();
        }
    }

    $('video').on('play', function () {
        if (currentVideo && currentVideo !== this) {
            currentVideo.pause();
        }
        currentVideo = this;
    });

    $(window).on('scroll', function () {
        let windowHeight = $(window).height();
        let scrollTop = $(window).scrollTop();
        let current = null;

        $('video').each(function () {
            let videoTop = $(this).offset().top;
            let videoHeight = $(this).height();

            if (videoTop >= scrollTop && videoTop < scrollTop + windowHeight) {
                if (!current) {
                    current = this;
                }
                $(this).addClass('current-video');
            } else {
                $(this).removeClass('current-video');
                $(this).get(0).pause(); // 暂停不在视口内的视频
            }
        });

        if (current) {
            playVideo(current);
        } else if (currentVideo) {
            currentVideo.pause();
        }
    });
});